All files / web/src/app/api/flowchart-workshop/sessions/[id]/save route.ts

0% Statements 0/261
0% Branches 0/1
0% Functions 0/1
0% Lines 0/261

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { and, eq } from 'drizzle-orm'
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { db, schema } from '@/db'
import { getUserId } from '@/lib/viewer'
import { validateFlowchartStructure } from '@/lib/flowcharts/validator'
import { generateFlowchartEmbeddings, EMBEDDING_VERSION } from '@/lib/flowcharts/embedding'
import { invalidateEmbeddingCache } from '@/lib/flowcharts/embedding-search'

/**
 * POST /api/flowchart-workshop/sessions/[id]/save
 * Save the current draft to a teacher flowchart
 *
 * If the session has a flowchartId, updates that flowchart (or creates a new version if published).
 * Otherwise, creates a new teacher flowchart.
 *
 * Returns: { flowchart: TeacherFlowchart, session: WorkshopSession }
 */
export const POST = withAuth(async (_request, { params }) => {
  try {
    const { id } = (await params) as { id: string }
    const userId = await getUserId()

    // Get the session
    const session = await db.query.workshopSessions.findFirst({
      where: and(eq(schema.workshopSessions.id, id), eq(schema.workshopSessions.userId, userId)),
    })

    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 })
    }

    // Check if expired
    if (session.expiresAt && new Date(session.expiresAt) < new Date()) {
      return NextResponse.json({ error: 'Session has expired' }, { status: 410 })
    }

    // Validate draft exists
    if (!session.draftDefinitionJson || !session.draftMermaidContent) {
      return NextResponse.json(
        { error: 'No draft to save - generate or refine first' },
        { status: 400 }
      )
    }

    // Validate the draft structure
    let definition
    try {
      definition = JSON.parse(session.draftDefinitionJson)
    } catch {
      return NextResponse.json({ error: 'Invalid draft definition JSON' }, { status: 400 })
    }

    const structureValidation = validateFlowchartStructure(definition)
    if (!structureValidation.valid) {
      return NextResponse.json(
        {
          error: 'Draft validation failed',
          details: structureValidation.errors,
        },
        { status: 400 }
      )
    }

    const now = new Date()
    let flowchart

    // If editing a published flowchart in-place (via linkedPublishedId)
    if (session.linkedPublishedId) {
      const existing = await db.query.teacherFlowcharts.findFirst({
        where: and(
          eq(schema.teacherFlowcharts.id, session.linkedPublishedId),
          eq(schema.teacherFlowcharts.userId, userId),
          eq(schema.teacherFlowcharts.status, 'published')
        ),
      })

      if (!existing) {
        return NextResponse.json({ error: 'Linked published flowchart not found' }, { status: 404 })
      }

      // Generate new embeddings for the updated content
      let embedding: Buffer | null = null
      let promptEmbedding: Buffer | null = null
      try {
        const result = await generateFlowchartEmbeddings({
          title: session.draftTitle || existing.title,
          description: session.draftDescription,
          topicDescription: session.topicDescription,
          difficulty: session.draftDifficulty,
        })
        embedding = result.embedding
        promptEmbedding = result.promptEmbedding
      } catch (embeddingError) {
        console.error('Failed to generate embeddings:', embeddingError)
      }

      // Update the published flowchart directly
      const [updated] = await db
        .update(schema.teacherFlowcharts)
        .set({
          title: session.draftTitle || existing.title,
          description: session.draftDescription,
          emoji: session.draftEmoji,
          difficulty: session.draftDifficulty,
          definitionJson: session.draftDefinitionJson,
          mermaidContent: session.draftMermaidContent,
          version: existing.version + 1,
          embedding,
          promptEmbedding,
          embeddingVersion: embedding ? EMBEDDING_VERSION : null,
          updatedAt: now,
          // Keep status as 'published' and publishedAt unchanged
        })
        .where(eq(schema.teacherFlowcharts.id, existing.id))
        .returning()

      flowchart = updated

      // Mark session as completed and delete it (optional cleanup)
      await db
        .update(schema.workshopSessions)
        .set({
          state: 'completed',
          updatedAt: now,
        })
        .where(eq(schema.workshopSessions.id, id))

      // Invalidate embedding cache
      if (embedding) {
        invalidateEmbeddingCache()
      }

      // Get updated session
      const updatedSession = await db.query.workshopSessions.findFirst({
        where: eq(schema.workshopSessions.id, id),
      })

      return NextResponse.json({
        flowchart,
        session: updatedSession,
        // Flag to tell the client this was an in-place update (skip publish step)
        alreadyPublished: true,
      })
    }

    // If editing an existing flowchart (legacy path)
    if (session.flowchartId) {
      const existing = await db.query.teacherFlowcharts.findFirst({
        where: and(
          eq(schema.teacherFlowcharts.id, session.flowchartId),
          eq(schema.teacherFlowcharts.userId, userId)
        ),
      })

      if (!existing) {
        return NextResponse.json({ error: 'Original flowchart not found' }, { status: 404 })
      }

      // If published, create a new version
      if (existing.status === 'published') {
        const [newVersion] = await db
          .insert(schema.teacherFlowcharts)
          .values({
            userId,
            title: session.draftTitle || existing.title,
            description: session.draftDescription || existing.description,
            emoji: session.draftEmoji || existing.emoji,
            difficulty: session.draftDifficulty || existing.difficulty,
            definitionJson: session.draftDefinitionJson,
            mermaidContent: session.draftMermaidContent,
            version: existing.version + 1,
            parentVersionId: existing.id,
            status: 'draft',
            createdAt: now,
            updatedAt: now,
          })
          .returning()

        flowchart = newVersion

        // Update session to point to new version
        await db
          .update(schema.workshopSessions)
          .set({
            flowchartId: newVersion.id,
            state: 'completed',
            updatedAt: now,
          })
          .where(eq(schema.workshopSessions.id, id))
      } else {
        // Update existing draft
        const [updated] = await db
          .update(schema.teacherFlowcharts)
          .set({
            title: session.draftTitle || existing.title,
            description: session.draftDescription,
            emoji: session.draftEmoji,
            difficulty: session.draftDifficulty,
            definitionJson: session.draftDefinitionJson,
            mermaidContent: session.draftMermaidContent,
            updatedAt: now,
          })
          .where(eq(schema.teacherFlowcharts.id, existing.id))
          .returning()

        flowchart = updated

        // Update session state
        await db
          .update(schema.workshopSessions)
          .set({
            state: 'completed',
            updatedAt: now,
          })
          .where(eq(schema.workshopSessions.id, id))
      }
    } else {
      // Create new flowchart
      const [newFlowchart] = await db
        .insert(schema.teacherFlowcharts)
        .values({
          userId,
          title: session.draftTitle || 'Untitled Flowchart',
          description: session.draftDescription,
          emoji: session.draftEmoji || '📊',
          difficulty: session.draftDifficulty,
          definitionJson: session.draftDefinitionJson,
          mermaidContent: session.draftMermaidContent,
          createdAt: now,
          updatedAt: now,
        })
        .returning()

      flowchart = newFlowchart

      // Update session to link to the new flowchart
      await db
        .update(schema.workshopSessions)
        .set({
          flowchartId: newFlowchart.id,
          state: 'completed',
          updatedAt: now,
        })
        .where(eq(schema.workshopSessions.id, id))
    }

    // Get updated session
    const updatedSession = await db.query.workshopSessions.findFirst({
      where: eq(schema.workshopSessions.id, id),
    })

    return NextResponse.json({
      flowchart,
      session: updatedSession,
    })
  } catch (error) {
    console.error('Failed to save workshop draft:', error)
    return NextResponse.json({ error: 'Failed to save draft' }, { status: 500 })
  }
})